#!/usr/bin/env python
# -*- coding: utf8 -*-
import base64
import sys
import os
from base64 import b64encode, b64decode
import codecs
import json

from cryptography.hazmat.primitives.ciphers.algorithms import AES

JSON_EXT = '.json'
ENCODE_METHOD = 'utf-8'


class MyEncoder(json.JSONEncoder):

    def default(self, obj):
        """
        只要检查到了是bytes类型的数据就把它转为str类型
        :param obj:
        :return:
        """
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        return json.JSONEncoder.default(self, obj)


class JSONWriter:

    def __init__(self, filename, shapes):
        self.shapes = shapes
        self.filename = filename

    def save(self, filename, imageHeight, imageWidth, imageData,
             lineColor, fillColor, flags=None):
        # print("json保存", filename, imageHeight, imageWidth,
        # lineColor, fillColor)
        if imageData is not None:
            imageData = base64.b64encode(imageData).decode('utf-8')
        if flags is None:
            flags = {}
            # print("json1", self.shapes)

        data = dict(
            version=json.__version__,
            flags=flags,
            shapes=self.shapes,
            lineColor=lineColor,
            fillColor=fillColor,
            imagePath=filename,
            imageData=imageData,
            imageHeight=imageHeight,
            imageWidth=imageWidth,
        )
        # print("json2", self.filename)
        # pc = prpcrypt()
        print("libs/json_io", data)

        with open(self.filename, 'a') as f:
            json.dump(data, f, ensure_ascii=False, indent=2, cls=MyEncoder)
        # print("json3")


class JSONReader:

    def __init__(self, filepath):
        self.shapes = []
        self.filepath = filepath
        self.verified = False
        try:
            self.parseJSONFormat()
        except:
            # print("json显示-错误")
            pass

    def getShapes(self):
        # print("label5",self.shapes, type(self.shapes))
        return self.shapes

    def addShape(self, label, polygon_points, difficult):
        points = []
        # print("label1",label)
        for polygon_list in polygon_points:
            # print("label1-1", polygon_list,type(polygon_list))
            points.append(tuple(polygon_list))
        self.shapes.append((label, points, None, None, difficult))

    def parseJSONFormat(self):
        assert self.filepath.endswith(JSON_EXT), "Unsupport file format"
        with open(self.filepath, 'r', encoding='utf-8') as jsonfile:
            ret_dic = json.load(jsonfile)
            for json_dic in ret_dic['shapes']:
                label = json_dic["label"]
                polygon_points = json_dic["points"]
                # print("label1-2",polygon_points,type(polygon_points))
                self.addShape(label, polygon_points, False)
        return True
